#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>

const static std::string defaultfilepath = "./";
const static std::string defaultfilename = "dictionary.txt";
const static std::string defaultsep = ": ";
class Dictionary
{
    bool SplitString(const std::string &line, std::string *key, std::string *value, const std::string &sep = defaultsep)
    {
        auto pos = line.find(sep);
        if (pos == line.npos)
            return false;
        *key = line.substr(0, pos);
        *value = line.substr(pos + sep.size());
        if (key->empty() || value->empty())
            return false;
        return true;
    }
    void Load()
    {
        std::string file = _filepath + _filename;
        std::ifstream in(file.c_str());
        if (!in.is_open())
        {
            std::cerr << "file open failed" << std::endl;
            exit(-1);
        }
        std::string line;
        while (std::getline(in, line))
        {
            // apple: 苹果
            std::string key;
            std::string value;
            if (SplitString(line, &key, &value))
            {
                _dictionary.insert(std::make_pair(key, value));
            }
        }
        in.close();
    }

public:
    Dictionary(const std::string &filepath = defaultfilepath, const std::string &filename = defaultfilename)
        : _filepath(filepath), _filename(filename)
    {
        Load();
    }
    std::string translate(const std::string &str)
    {
        auto posit = _dictionary.find(str);
        if (posit == _dictionary.end())
            return "None";
        else
            return posit->second;
    }
    ~Dictionary()
    {
    }

private:
    std::unordered_map<std::string, std::string> _dictionary;
    const std::string _filepath;
    const std::string _filename;
};